/*
 * PlainTextHandler.java
 *
 * Created on March 22, 2008, 9:50 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.afaker.searth.core.index.handler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

/**
 *
 * @author bruce
 */
public class PlainTextHandler extends DocumentHandler{
    
    /** Creates a new instance of PlainTextHandler */
    public PlainTextHandler() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }
    
    public Document getDocument(File file) {
        FileReader reader = null;
        String fileName = file.getName();
        int dotIndex = fileName.lastIndexOf(".");
        String extention = null;
        if((dotIndex < fileName.length()) && (dotIndex > 0)) {
            extention = fileName.substring(dotIndex + 1);
            extention = extention.toLowerCase();
        }
        if(extention == null || extention.trim().equals(""))
            return null;
        try {
            reader = new FileReader(file);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        int b = 0;
        StringBuffer buffer = new StringBuffer();
        try {
            while((b = reader.read()) > -1){
                buffer.append((char)b);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        Document doc = new Document();
        doc.add(new Field("path",file.getAbsolutePath(),
                Field.Store.YES,Field.Index.TOKENIZED));
        doc.add(new Field("content",new StringReader(file.getAbsolutePath() + buffer.toString())));
        String size = String.valueOf(file.length()/1024.0) + "KB";
        float s = file.length()/1024.0f/1024.0f;
        float l = file.length()/1024.0f;
        if(s >= 1)
            size = String.valueOf(s) + "M";
        else
            size = String.valueOf(l) + "KB";
        doc.add(new Field("format",extention,Field.Store.YES,Field.Index.TOKENIZED));
        doc.add(new Field("size",size,Field.Store.YES,Field.Index.UN_TOKENIZED));
        doc.add(new Field("modified",String.valueOf(file.lastModified()),
                //DateTools.timeToString(file.lastModified(), DateTools.Resolution.MINUTE),
                Field.Store.YES, Field.Index.UN_TOKENIZED));
        return doc;
    }
    
}
